import { constantRoutes, asyncRoutes } from '@/router'
import { generateTitle } from '@/utils/i18n'

function isInAcl(routeName, routerArr) {
  for (let i = 0; i < routerArr.length; i++) {
    if (routeName === routerArr[i]) {
      return true
    }
  }
  return false
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routerArr
 */
export function filterAsyncRoutes(routerArr) {
  console.log(routerArr)
  const res = []
  asyncRoutes.forEach(route => {
    const tmp = { ...route }
    if (isInAcl(tmp.path, routerArr)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children)
      }
    }
    res.push(tmp)
  })

  return res
}

const state = {
  routes: [],
  permissions: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  generateRoutes({ commit }, menuListFromBackend) {
    return new Promise(resolve => {
      const res = initMenus(menuListFromBackend)
      commit('SET_ROUTES', res)
      resolve(res)
    })
  }
}

export function initMenus(menuListFromBackend) {
  const menuRouters = []
  asyncRoutes.forEach((m, i) => {
    if (m.path !== '*' && m.meta.route !== undefined) {
      const item = getBackendItem(m.meta.route, menuListFromBackend)
      if (item != null) {
        // 有下级
        if (m.children && m.children.length > 0) {
          const children = []
          m.children.forEach((mc, ic) => {
            const childrenItem = getBackendItem(mc.meta.route, item['children'])
            if (childrenItem != null) {
              mc.meta.title = childrenItem['title']
              children.push(mc)
            } else if (mc.hidden === true) {
              children.push(mc)
            }
          })
          m.children = children
        }
        m.meta.title = item['title']
        menuRouters.push(m)
      }
    }

    if (m.path === '*') {
      menuRouters.push(m)
    }
  })

  return menuRouters
}

function getBackendItem(search, object) {
  for (let i = 0; i < object.length; i++) {
    if (search === object[i]['path']) {
      return object[i]
    }
  }
  return null
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
